import utils from '../../utils/util';

// https://kptest.ckjr001.com/kpv2p/lj7l/?#/homePage/form?cId=-1&extId=52478&ckFrom=12&isFromInvite=0&pId=&relType=19&type=1&isGoBack=1&specsType=1
//https://kptest.ckjr001.com/kpv2p/lj7l/?#/homePage/form?cId=-1&extId=52478&ckFrom=12&isFromInvite=0&pId=&relType=19&type=1&isGoBack=1&goodsRoomId=26557&specsType=1
// https://kptest.ckjr001.com/kpv2p/lj7l/?#/homePage/form?relId=7159&relType=1&type=2
//enableEdit  1不可编辑  2 可以编辑
// enableRepeatedCollect  1可以重复采集  -1不可
// isRepeatedCollect  自动获取信息 1关闭  0开启
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    isShow: {
      type: Boolean,
      value: false
    },
    ckFrom: { //产品的类型 商城就是12
      type: Number,
      optionalTypes: [String],
      value: 0
    },
    extId: { //商品的id
      type: Number,
      optionalTypes: [String],
      value: 0
    },
    relId: { //表单的id（报名表单  调研表单 产品类型关联表单）
      type: Number,
      optionalTypes: [String],
      value: 0
    },
    relType: { // 1报名保单 2调研表单  3其他商品类型的表单（ckFrom去map配置config的formRelateType）
      type: Number,
      optionalTypes: [String],
      value: 1
    },
    type: { //1产品关联表单跳转  2直接表单填写
      type: Number,
      optionalTypes: [String],
      value: 1
    },

    socialRoomId: { //直播社群id
      type: Number,
      optionalTypes: [String],
      value: 0
    },
    detailId: { //直播间id
      type: Number,
      optionalTypes: [String],
      value: 0
    },
    otherParams: { //其他的删除，提交成功的时候回调抛给父组件
      type: Object,
      value: {}
    }

  },

  lifetimes: {
    attached: function () {},
    detached: function () {}
  },

  /**
   * 组件的初始数据
   */
  data: {
    hadSubmit: false,
    repeatCollect: false,
    isAutoCollect: false,
    formList: [],
  },

  /**
   * 组件的方法列表
   */
  methods: {
    //弹窗打开
    onOpen() {
      this.getFormData();
      this._startTimeTmp = new Date().getTime();
    },
    formSubmit(e) {
      console.log("formSubmit", e);
      let formData = e.detail; //表单数据
      let sendData = {
        fId: this._fId,
        isSubmitForm: this._isSubmitForm,
        content: formData,
        relId: this.data.relId,
        relType: this.data.relType,
        type: this.data.type,
        duration: (new Date().getTime() - this._startTimeTmp) / 1000, //统计提交用时
      }
      utils.post("k12/forms/submitForm", sendData).then(res => {
        // wx.showToast({
        //   title: '提交成功',
        //   icon: "none"
        // });
        this._submitFormRes = res || {};
        if (this.data.relType != 2 || this.data.type == 1) {
          // 非调研表单 || 关联表单
          this.setData({
            isShow: false
          });
          wx.showToast({
            title: '填写成功',
            duration:2000
          })
        }
        if (this.data.relType == 2 && this.data.type == 2) {
          //调研表单
          this.setData({
            isShow: false
          });
          this._getPrize();
          wx.showToast({
            title: '填写成功',
            duration:2000
          })
        }
        this.triggerEvent("submitSuccess", {
          ...this.data.otherParams
        });
      }).catch(() => {
        this.triggerEvent("submitFail");
      });
    },

    //获取优惠券积分
    _getPrize() {
      utils.get(`k12/forms/formSubmitSuccess/${this.data.relId}`, {},false).then(res => {
        if (res.submitShowType == 1) {
          let giveType = res.giveType ? res.giveType : [];
          let couponList = res.coupons && res.coupons.length > 0 ? res.coupons : [];
          let isGetPoints = this._submitFormRes.isSendPoints == 2 && giveType.includes(2);
          let isGetCoupons = couponList.length && giveType.includes(1);
          if (isGetPoints || isGetCoupons) {
            wx.showToast({
              title: '相关奖励已发送',
            })
          }
        } else {
          wx.showToast({
            title: '提交成功',
          })
        }
      })
    },
    //获取表单的数据
    getFormData() {
      let sendData = {
        relId: this.data.relId, //关联的id(某个产品绑定了表单，那么对应的就是 prodId)
        relType: this.data.relType, ///来自哪个产品 1 报名表单 2 调研表单 其他：产品类型
        type: this.data.type
      }
      if (this.data.socialRoomId) {
        sendData.socialRoomId = this.data.socialRoomId;
      }
      if (this.data.detailId) {
        sendData.detailId = this.data.detailId;
      }
      utils.get('k12/forms/formShow', sendData).then(res => {
        if (!res) {
          wx.showToast({
            title: '未找到该表单,请刷新重试！',
            icon: "error"
          });
          return;
        }
        res.content = res.content || [];
        res.content.forEach((item, index) => {
          //单选或者多选的时候选中其他 然后构造一个选项
          if (item.type == 8) {
            if (item.isOtherOption) {
              let idx = item.option.findIndex(option => option.isOtherOption == 1);
              if (idx == -1) {
                item.option.push({
                  key: '其他',
                  isOtherOption: 1
                });
              }
            }
            item._optionKeys = [];
            item.option.forEach(option => {
              item._optionKeys.push(option.key);
            })
          } else if (item.type == 14) {
            //下拉框
            item.seOption = [
              []
            ];
            item.option.forEach(option => {
              item.seOption[0].push(option.key);
            });
            // item.optIndex = "";
          }
        })
        this._fId = res.fId;
        this._isSubmitForm = res.isSubmitForm;
        console.log("formList", res.content)
        this.setData({
          hadSubmit: res.isSubmitForm,
          repeatCollect: res.enableRepeatedCollect == -1 ? false : true,
          isAutoCollect: res.isRepeatedCollect ? false : true,
          formList: res.content
        })
      })
    }
  }
})